import { defineStore } from 'pinia';
import { ref } from 'vue';
import { useStorage } from '@vueuse/core';
import { IUserInfo } from '@/types/user';
import router from '@/router'
// 用户信息
export const userStore = defineStore("userStore", () => {
  type tokenType = "token" | "refreshToken";

  // token 登录token
  const token = useStorage('token', '');
  // refreshToken 刷新token
  const refreshToken = useStorage('refreshToken', '');
  // 用户信息
  const userInfo = ref({});
  // 登录标识
  const isLogin = ref(token.value.length > 0);

  /**
   * 设置登录状态
   */
  function setLoginStatus(status: boolean) {
    isLogin.value = status;
    if (!isLogin.value) {
      router.replace('/login?toPage=' + router.currentRoute.value.fullPath)
    }
  }

  /**
   * 设置用户信息
   */
  function setUserInfo(info: IUserInfo) {
    userInfo.value = info;
  }
  /**
   * 设置token
   */
  function setToken(tokenType: tokenType, t: string) {
    if (tokenType === "token")
      token.value = t;
    else if (tokenType === "refreshToken")
      refreshToken.value = t;
    else
      throw new Error("tokenType is error");
  }

  /**
   * 统一设置
   */

  function setAll(info: IUserInfo, tokenType: tokenType, t: string, login: boolean) {
    setUserInfo(info);
    setToken(tokenType, t);
    setLoginStatus(login);
  }

  return {
    token,
    refreshToken,
    userInfo,
    isLogin,
    setLoginStatus,
    setUserInfo,
    setToken,
    setAll,
  }

})